package com.sgb.kjwl.view.ui.fragment.self;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentMyOfferBinding;
import com.sgb.kjwl.di.self.DaggerSelfFragComponent;
import com.sgb.kjwl.di.self.SelfFragModule;
import com.sgb.kjwl.model.entity.self.MyOfferEntity2;
import com.swgk.core.base.model.entity.ListResponse;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.activity.self.carMaster.MyOfferDetailsActivity;
import com.sgb.kjwl.view.ui.activity.transport.BiddingOrderDetailsActivity;
import com.sgb.kjwl.view.ui.activity.transport.CargoQuotationActivity;
import com.sgb.kjwl.view.ui.activity.transport.owner.TransportOrderDetailOwnerActivity;
import com.sgb.kjwl.view.ui.adapter.self.carMasters.MyOfferAdapter;
import com.sgb.kjwl.viewmodel.self.carMakers.MyOfferFragModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * @author: 杨畔
 * @date: 2021/2/6 16:42
 * @Description: 我的报价内容页
 */
public class MyOfferFragment extends AppLazyFragment implements MyOfferAdapter.RightBtnListener, MyOfferAdapter.CheckOrderListener {
    @Inject
    MyOfferFragModel viewModel;
    FragmentMyOfferBinding binding;
    //
    private Activity mActivity;
    //页面状态:0全部  1已报价  2待支付  3已支付 4超时未支付 5货主未同意
    private int mStatus;
    private List<MyOfferEntity2> mList;
    private MyOfferAdapter mAdapter;
    private Map<String, Object> mMap;


    public static MyOfferFragment newInstance(int type) {
        MyOfferFragment fragment = new MyOfferFragment();
        Bundle args = new Bundle();
        args.putInt(RouterKey.TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        super.setupFragmentComponent(appComponent);
        DaggerSelfFragComponent.builder()
                .appComponent(appComponent)
                .selfFragModule(new SelfFragModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        mActivity = (Activity) context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_my_offer, container, false);
        binding.setLifecycleOwner(this);
        initPage();
        initViews();
        initEvent();
        return binding.getRoot();
    }

    private void initPage() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            int status = getArguments().getInt(RouterKey.TYPE, 0);
//            1已报价  2待支付  3已支付 4超时未支付 5货主未同意
            switch (status) {
                case 0://全部
                case 1://已报价
                case 2://报价已同意
                    mStatus = status;
                    break;
                case 3://报价未同意
                case 4://货主未同意
                    mStatus = 5;
                    break;
                case 5://超时未支付
                    mStatus = 4;
                    break;
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mMap = new HashMap<>();
        int type = UserOperating.getInstance().getUserIdentity();
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        String userNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        if (type == 1) {//企业
            mMap.put("companyNo", companyNo);
            mMap.put("offerType", 1);
        } else if (type == 2) {//团队
            mMap.put("teamNo", companyNo);
            mMap.put("offerType", 2);
        } else {//个人
            mMap.put("userNo", userNo);
            mMap.put("offerType", 3);
        }
        viewModel.getMyOfferOrder(mActivity, mStatus, true, mMap);
    }

    private void initViews() {
        mList = new ArrayList<>();
        mAdapter = new MyOfferAdapter(mList);
        binding.rvMyOffer.setLayoutManager(new LinearLayoutManager(getActivity()));
        DividerDecoration.builder(mActivity)
                .colorRes(R.color.transparent)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(binding.rvMyOffer);
        mAdapter.bindToRecyclerView(binding.rvMyOffer);
        binding.rvMyOffer.setAdapter(mAdapter);
        mAdapter.setBtnListener(this::onRightBtnClick);
        mAdapter.setCheckListener(this::onCheckOrderClick);

    }

    @SuppressLint("FragmentLiveDataObserve")
    private void initEvent() {
        mAdapter.setEmptyView(R.layout.layout_null_list_logistics);
        binding.refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                viewModel.getMyOfferOrder(mActivity, mStatus, false, mMap);
                binding.refreshLayout.finishLoadMore();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                viewModel.getMyOfferOrder(mActivity, mStatus, true, mMap);
                binding.refreshLayout.finishRefresh();
            }
        });
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
                    if (mList.size() > position) {
                        MyOfferDetailsActivity.start(mActivity, mList.get(position).getGoodsOfferNo(), false);
                    }
                }
        );
//        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
//            if (view.getId() == R.id.check_order) {
//                MyOfferEntity2 entity = mList.get(position);
//                orderBtnClick(entity);
//            }
//        });


        viewModel.ldRecord.observe(this, this::showList);
    }

/*    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getChange(LogisticsEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_REFRESH_MY_OFFER_LIST) {
            viewModel.getMyOfferOrder(mActivity,mStatus , true);
        }
    }*/

    /**
     * 列表按钮点击
     */
    private void orderBtnClick(MyOfferEntity2 entity) {
        int offerStatus = entity.getOfferStatus();
        //报价状态：1已报价（更新报价） 2报价已同意） 3已支付(查看运输订单)
        switch (offerStatus) {
            case 1:
                updateOffer(entity);
                break;
            case 2:
//                checkPay(entity);
                //查看订单
                BiddingOrderDetailsActivity.start(getContext(), entity.getOrderNo(), 1);
                break;
            case 3:
                if (!TextUtils.isEmpty(entity.getOrderNo()))
                    toOrderDetail(entity.getOrderNo());
                break;
        }
    }

    /**
     * 更新报价
     */
    private void updateOffer(MyOfferEntity2 entity) {
        int type = UserOperating.getInstance().getUserIdentity();
        if (!TextUtils.isEmpty(entity.getGoodsSourceNo()))
            CargoQuotationActivity.start(getActivity(), entity.getGoodsSourceNo(), true, type == 1 || type == 2 ? false : true, entity.getFreight());
    }

    /**
     * 支付信息费
     */
    private void checkPay(MyOfferEntity2 entity) {
        //车辆状态及资金账户开通校验
        viewModel.checkCarInfo(getActivity(), entity);
    }

    /**
     * 运输订单详情
     */
    private void toOrderDetail(String orderNo) {
        Intent intent = new Intent(getActivity(), TransportOrderDetailOwnerActivity.class);
        intent.putExtra("isGoodsOwner", 0);//这里是车主，传值：0
        intent.putExtra("no", orderNo);//订单编号
        startActivity(intent);
    }

    public void showList(ListResponse<List<MyOfferEntity2>> listResponse) {
        if (listResponse == null || !listResponse.isLoadSuccess()) return;
        if (listResponse.getCurrentPage() <= 1) {
            mList.clear();
        }
        if (listResponse.getList() != null && listResponse.getList().size() > 0) {
            mList.addAll(listResponse.getList());
        }
        mAdapter.notifyDataSetChanged();

        if (listResponse.haveMoreData()) {
            binding.refreshLayout.resetNoMoreData();
        } else {
            binding.refreshLayout.finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    public void onRightBtnClick(MyOfferEntity2 entity) {
        if (entity != null)
            orderBtnClick(entity);
    }


    @Override
    public void onCheckOrderClick(MyOfferEntity2 entity) {
        if (entity != null)
            orderBtnClick(entity);
    }

    @Override
    protected void onLazyLoad() {

    }
}
